package practice;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Named;

import static practice.OfyService.ofy;
import com.google.api.server.spi.config.Api;
import com.google.api.server.spi.config.ApiMethod;
import com.google.api.server.spi.config.ApiMethod.HttpMethod;

@Api(name = "config")
public class ConfigApi {
	
	@ApiMethod(path = "getAllConfig", httpMethod = HttpMethod.GET)
	public Map<String, ConfigProp> getAllConfig(@Named("useMemcache") boolean useMemcache) {
		List<String> ids = new ArrayList<>();
		
		for (int i = 0; i < 10; i++) {
			ids.add("key" + i);
		}
		
		Map<String, ConfigEntity> entityMap = ofy().cache(useMemcache).load().type(ConfigEntity.class).ids(ids);
		
		Map<String, ConfigProp> propMap = new HashMap<>();
		
		for (String key : entityMap.keySet()) {
			ConfigProp configProp = entityMap.get(key).toProp();
			
			propMap.put(key, configProp);
		}
		
		return propMap;
	}
	
	@ApiMethod(path = "putAllConfig", httpMethod = HttpMethod.PUT)
	public void putAllConfig() {		
		
		List<ConfigEntity> entities = new ArrayList<>();
		for (int i = 0; i < 10; i++) {
			ConfigEntity entity = new ConfigEntity();
			entity.id = "key" + i;
			entity.json = System.currentTimeMillis() + "";
			entities.add(entity);
		}
		
		ofy().save().entities(entities).now();
	}
}
